﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using StorageCleanup.Resources;

using RPCComponent;

namespace StorageCleanup
{
	public partial class MainPage : PhoneApplicationPage
	{
		long total;
		CleanupLocation[] locations;

		// Constructor
		public MainPage ()
		{
			InitializeComponent();

			locations = new CleanupLocation[] {
				new CleanupLocation(@"C:\Data\SharedData\EdmCache\Lib", description:"Store app package cache"),
				new CleanupLocation(@"C:\Data\SharedData\Enterprise", "Files from installing Enterprise apps"),
				new CleanupLocation(@"C:\Data\SharedData\dushared\PackagesToInstall", "Device update packages"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\COMMSAPPLICATIONS\Temp", description:"Voicemail message cache"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\INTERNETEXPLORER\INetCache", true, "Temporary Internet files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\INTERNETEXPLORER\Temp", description:"Internet Explorer temp files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\Temp\OneNote", description:"OneNote temp media files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\Temp\ZipView", description:"Zip file content cache"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\REALWORLD-BINGCLIENT\Local\Shared\WebSearch\Stores\VisionResultsStore", description:"Bing Vision image cache"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\REALWORLD-BINGCLIENT\Local\Shared\WebSearch\Stores", "*.dat", "Bing Vision and Music history"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\REALWORLD-BINGCLIENT\INetCache", true, "Bing temp Internet files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\COMMSAPPLICATIONS\INetCache", true, "Email temp Internet files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\INetCache", true, "Office temp Internet files"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\Local\SampleDocs", description:"Office sample documents"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\Local\SavedAttachments", description:"Office documents from email"),
				new CleanupLocation(@"C:\Data\Users\DefApps\AppData\OFFICE\Roaming\Templates", description:"Office document templates")
			};

			total = 0L;

			// Sample code to localize the ApplicationBar
			//BuildLocalizedApplicationBar();
		}

		private void PhoneApplicationPage_Loaded (object sender, RoutedEventArgs e)
		{
			// Check the Samsung component and SD card presence...
			try
			{
				CRPCComponent.Initialize();
			}
			catch
			{
				MessageBox.Show("Warning: Failed to initialize Samsung RPC Component! Some files may not be deletable.");
			}
			try
			{
				if (!Directory.Exists(CleanupLocation.SD))
					Directory.CreateDirectory(CleanupLocation.SD);
				if (Directory.Exists(CleanupLocation.SD))
					Directory.Delete(CleanupLocation.SD);
			}
			catch
			{
				MessageBox.Show("Unable to access an SD card. Some files may not be deletable.");
			}
			// Initialize the list of cleanup locations.
			foreach (CleanupLocation cl in locations)
			{
				stackview.Children.Add(cl);
				total += cl.Compute();
			}
			txtTotal.Text = "Up to " + CleanupLocation.getReadable(total) + " can be freed";
			btnClean.IsEnabled = true;
		}

		private void btnClean_Click (object sender, RoutedEventArgs e)
		{
			long subtotal = 0L;
			int count = 0;
			foreach (CleanupLocation cl in locations)
			{
				if (cl.Selected)
				{
					subtotal += cl.Bytes;
					count += cl.Count;
				}
			}
			if (0 == count)
				MessageBox.Show("No files selected for deletion! Select some folders with files for deletion first.");
			else if (MessageBoxResult.OK == MessageBox.Show("Are you sure you want to delete " + count + " files (" +
				CleanupLocation.getReadable(subtotal) + ")? This action cannot be undone! Press OK to continue.",
				"PLEASE CONFIRM", MessageBoxButton.OKCancel))
			{
				StringBuilder b = new StringBuilder();
				foreach (CleanupLocation cl in locations)
				{
					if (cl.Selected)
					{
						total -= cl.Bytes;
						// TODO: Create a proper report with the returned strings
						b.AppendLine(cl.DoCleanup());
						total += cl.Compute();
					}
				}
				if (b.Length > 1000)
				{
					b.Length = 1000;
					b.Append("\n\nTruncated...");
				}
				MessageBox.Show(b.ToString());
				txtTotal.Text = "Up to " + CleanupLocation.getReadable(total) + " can be freed";
			}
		}

		// Sample code for building a localized ApplicationBar
		//private void BuildLocalizedApplicationBar()
		//{
		//    // Set the page's ApplicationBar to a new instance of ApplicationBar.
		//    ApplicationBar = new ApplicationBar();

		//    // Create a new button and set the text value to the localized string from AppResources.
		//    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
		//    appBarButton.Text = AppResources.AppBarButtonText;
		//    ApplicationBar.Buttons.Add(appBarButton);

		//    // Create a new menu item with the localized string from AppResources.
		//    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
		//    ApplicationBar.MenuItems.Add(appBarMenuItem);
		//}
	}
}